package com.first.orange.controller;

import com.first.orange.beans.*;
import com.first.orange.service.PayService;
import com.first.orange.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created:  2021/7/5.
 *
 * Author: wuqilong
 *
 * Description: 订单结算控制类
 */
@Controller
public class OrderController {

    @Autowired
    PayService payService;

    @Autowired
    ProductService productService;

    /**
     * 全局变量：用户id
     */
    private Integer userId;

    /**
     * 全局变量：收货地址id
     */
    private Integer finalShopId;

    /**
     * 全局变量：运费
     */
    private Integer freight;

    /**
     * 全局变量：用户购买商品总价-不含运费
     */
    private Double productPrice;

    /**
     * 全局变量：用户购买商品总价-含运费
     */
    private Double sumPrice;

    /**
     * 全局变量：用户默认地址信息
     */
    private List<ShopAddress> shopAddressList;

    /**
     * @author : 武
     * @date : 2021/7/5
     * @return : java.lang.String
     * @description : 增加用户收货地址功能
     */
    @RequestMapping("/addAddress")
    @ResponseBody
    public boolean addAddress(HttpServletRequest request){
        ShopAddress shopAddress = new ShopAddress();
        shopAddress.setUserId(userId);
        shopAddress.setReceiverName(request.getParameter("receiverName"));
        shopAddress.setReceiverMobile(request.getParameter("receiverMobile"));
        shopAddress.setReceiverProvince(request.getParameter("receiverProvince"));
        shopAddress.setReceiverCity(request.getParameter("receiverCity"));
        shopAddress.setReceiverDistrict(request.getParameter("receiverDistrict"));
        shopAddress.setReceiverAddress(request.getParameter("receiverAddress"));

        return payService.addShopAddress(shopAddress);
    }

    /**
     * @author : 武
     * @date : 2021/7/6
     * @return : java.lang.String
     * @description : 展示用户所有收货地址功能-展示用户加入购物车且选中的商品信息或是立即购买的商品信息
     */
    @RequestMapping("/showShopAddress")
    public String showShopAddress(@RequestParam(required = false, defaultValue = "0") Integer shopId, Map<String, Object> map, @RequestParam(required = false, defaultValue = "1") Integer checked, HttpSession session){
        // 将全局变量中的价格置为0，防止刷新页面时不断累加
        freight = 0;
        productPrice = 0.00;
        sumPrice = 0.00;

        // 获取收货地址id，赋给finalShopId
        finalShopId = shopId;

        // 获取登录用户id
        UserLogin userLogin=(UserLogin) session.getAttribute("user");
        userId = userLogin.getUserId();

        // 展示用户所有收货地址
        map.put("shopAddresses", payService.queryAllShopAddress(userId));
        System.out.println(payService.queryAllShopAddress(userId));
        // 在地址卡片中展示默认地址信息
        shopAddressList = payService.queryDefaultShopAddress(shopId, userId);
        map.put("defaultShopAddresses", payService.queryDefaultShopAddress(shopId, userId));

        // 展示用户加入购物车且选中的商品信息
        map.put("carts", payService.queryCart(userId,checked));

        // 根据用户所处地区判断运费-江浙沪包邮-其余省份均10元
        if(shopAddressList == null || shopAddressList.size() <= 0) {
            freight = 0;
        } else {
            for (ShopAddress shopAddress : shopAddressList) {
                if ((shopAddress.getReceiverProvince().equals("江苏省")) ||
                        (shopAddress.getReceiverProvince().equals("浙江省")) ||
                        (shopAddress.getReceiverProvince().equals("上海市"))) {
                    freight = 0;
                } else {
                    freight = 10;
                }
            }
        }

        // 计算用户购买商品总价-不含运费
        List<Cart> cartList = payService.queryCart(userId,checked);
        for (Cart cart : cartList) {
            productPrice += cart.getAmount();
        }

        // 计算用户购买总花费-含运费
        sumPrice = productPrice + freight;
        map.put("freight",freight);
        map.put("productPrice",productPrice);
        map.put("sumPrice",sumPrice);
        map.put("checked",checked);

        return "home/pay";
    }

    /**
     * @author : 武
     * @date : 2021/7/6
     * @return : java.lang.String
     * @description : 删除用户收货地址
     */
    @RequestMapping("/delShopAddress")
    public String delShopAddress(@RequestParam Integer shopId, @RequestParam(required = false, defaultValue = "1") Integer checked){
        payService.delShopAddress(shopId);

        return "redirect:/showShopAddress?checked=" + checked;
    }

    /**
     * @author : 武
     * @date : 2021/7/6
     * @return : java.lang.String
     * @description : 修改用户默认收货地址
     */
    @RequestMapping("/setDefaultTag")
    public String setDefaultTag(@RequestParam Integer shopId,  @RequestParam(required = false, defaultValue = "1") Integer checked){
        // 修改默认地址
        payService.setDefaultTag1(shopId);

        // 将其余地址标识置为1
        payService.setDefaultTag2(shopId);

        return "redirect:/showShopAddress?checked=" + checked;
    }

    /**
     * @author : 武
     * @date : 2021/7/7
     * @return : java.lang.String
     * @description : 插入订单数据
     */
    @RequestMapping("/insertOrders")
    public String insertOrders(@RequestParam String logisticsName, @RequestParam(required = false, defaultValue = "1") Integer checked, Map<String, Object> map){
        List<Orders> orders = new ArrayList();

        // 计算用户购买商品总价-不含运费
        List<Cart> cartList = payService.queryCart(userId,checked);

        // 随机生成订单流水号
        String orderNum = "";
        Random random = new Random();
        //随机生成数字，并添加到字符串
        for(int i = 0;i < 8;i++){
            orderNum += random.nextInt(10);
        }

        // 循环插入订单数据
        for(int i = 0;i < cartList.size();i++){
            Orders order = new Orders();
            order.setOrderNum(orderNum);
            order.setUserId(userId);
            order.setReceiverName(shopAddressList.get(0).getReceiverName());
            order.setReceiverMobile(shopAddressList.get(0).getReceiverMobile());
            order.setReceiverProvince(shopAddressList.get(0).getReceiverProvince());
            order.setReceiverCity(shopAddressList.get(0).getReceiverCity());
            order.setReceiverDistrict(shopAddressList.get(0).getReceiverDistrict());
            order.setReceiverAddress(shopAddressList.get(0).getReceiverAddress());
            order.setLogisticsName(logisticsName);
            order.setProductId(cartList.get(i).getProductId());
            order.setPictureUrl(cartList.get(i).getPictureUrl());
            order.setProName(cartList.get(i).getProName());
            order.setPrice(cartList.get(i).getPrice());
            order.setQuantity(cartList.get(i).getQuantity());
            order.setFlavor(cartList.get(i).getFlavor());
            order.setPack(cartList.get(i).getPack());
            order.setAmount(cartList.get(i).getAmount());
            order.setChecked(cartList.get(i).getChecked());
            if(freight == 0){
                order.setFreight("包邮");
            } else {
                order.setFreight(Integer.toString(freight));
            }
            order.setPayment(sumPrice);
            order.setOrderStatus("已付款");

            orders.add(order);
        }

        // 调用insert语句插入数据库
        payService.insOrders(orders);

        // 调用updProductStock方法更新库存，月销量，总销量
        for(int i = 0;i < cartList.size();i++){
            Product product = productService.queryProductById(Integer.toString(cartList.get(i).getProductId()));
            int stock = product.getStock() - cartList.get(i).getQuantity();
            int productId = product.getProductId();
            int monthSales = product.getMonthSales() + cartList.get(i).getQuantity();
            int totalSales = product.getTotalSales() + cartList.get(i).getQuantity();
            payService.updProductStock(productId, stock, monthSales, totalSales);
        }

        // 跳转到支付页面
        //return "redirect:/end?checked=" + checked;
        return "redirect:/Alipay/to_alipay.do?in_name=" + orders.get(0).getReceiverName()
                + "&&in_phone=" + orders.get(0).getReceiverMobile() + "&&in_money=" + sumPrice
                + "&&shopId=" + finalShopId + "&&userId=" + userId + "&&checked=" + checked;
    }

}
